package com.dk.service.serviceImpl;

import com.dk.jwzx.JwzxHelper;
import com.dk.jwzx.bean.Student;
import com.dk.mapper.UserMapper;
import com.dk.pojo.User;
import com.dk.service.UserService;
import com.dk.util.JsonUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

@Service
public class UserServiceImpl implements UserService {
    private static final String USER="users";

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private Jedis jedis;

    public boolean haveUser(String id){
        //只有注册时候调用故不做缓存
        if(userMapper.checkUser(id)==1){
            return true;
        }
        return false;
    }

    public User getUser(String id) throws Exception {
        if(jedis.hexists(USER,id)){
            return JsonUtil.getObjectByJson(jedis.get(id),User.class);
        }else{
            User user= userMapper.queryUserById(id);
            jedis.hset(USER, user.getId(), JsonUtil.getJsonByObject(user));
            return user;
        }
    }

    public void saveUser(User user) throws JsonProcessingException {
        userMapper.saveUser(user);
        jedis.hset(USER, user.getId(), JsonUtil.getJsonByObject(user));
    }

    public void updateUser(User user) throws JsonProcessingException {
        userMapper.updateUser(user);
        jedis.hset(USER, user.getId(), JsonUtil.getJsonByObject(user));
    }

    public User updateStuId(String uid,String stuId) throws JsonProcessingException {
        User user= userMapper.queryUserById(uid);
        Student student= JwzxHelper.getStudentInfo(stuId);
        user.setName(student.getXm());
        user.setStuId(stuId);
        user.setClassNumber(student.getBj());
        user.setMajor(student.getZym());
        userMapper.updateUser(user);
        jedis.hset(USER, user.getId(), JsonUtil.getJsonByObject(user));
        return user;
    }
}
